/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/

#ifndef _FLEET_CTRL_CLIENT_HPP
#define _FLEET_CTRL_CLIENT_HPP

#include "MaCIClients.hpp"
#include "MachineCtrlClient.hpp"
#include "MachineCtrlTypes.hpp"
#include "MaCICtrlClient.hpp"

namespace MaCI{
  namespace MachineCtrl{

    typedef std::vector<std::string> TMachineNameList;
    typedef std::map<std::string,CMachineCtrlClient *> TMachines;  //MaCI-group name is the key that gives the right CMachineCtrlClient pointer

    class CFleetCtrlClient 
      :  private gim::CSync,
         private gim::CThread
    {
    public:
      


      /** Constructor
       *
       * Constructor which creates its own GIMI instance.
       *
       * Constructor makes a service discovery and creates clients for every services that is 
       * under given MaCI-group.
       *
       * @param[in] aGIMnetAPAddress         Address of GIMnet AP to connect
       * @param[in] aGIMnetAPPort            Port of GIMnet AP to connect
       * @param[in] aFleetName               Part of the MaCI-group that describes the fleet name.
       *                                     All the machines under the fleet will be constructed
       * @param[in] aContinuous              Continuosly doing servicediscovery and finding new machines
       *                                     to fleet
       */
      CFleetCtrlClient(std::string aGIMnetAPAddress,
                       unsigned int aGIMnetAPPort,
                       std::string aFleetName,
                       bool aContinuous = false);
      
      /**
       * Destructor
       */
      ~CFleetCtrlClient();

      /**
       * Connects and searches the fleet given at constructor.
       * If continuos mode is set, the thread watching the state of network is started also.
       *
       * @return  true if fleet is found and connected, otherwise false 
       */      
      bool ConnectFleet();
      /**
       * Update the state of the fleet by doing service discovery on the network, and adding
       * new services belonging to the fleet. If you are using continuous mode, don't need to call this 
       * function.
       *
       */
      void UpdateFleet();
      
      /**
       * Returns all the machine names found and constructed
       *
       * @return         A list of machine names (full MaCI group name)
       */
      TMachineNameList GetMachineNames();
        
      /**
       * Get the number of machines in fleet
       *
       * @return         Number of machines in fleet
       */
      unsigned int GetFleetSize();
      
      /**
       * Returns a pointer to a wanted machine, given by full MaCI group name.
       *
       * @param[in] aMachineName       The full MaCI group name of the wanted machine
       * @return                       Pointer to CMachineCtrlClient instance
       */
      CMachineCtrlClient *GetMachine(std::string aMachineName);

      /**
       * Returns a map of all machine beloging to the fleet. The key is the full MaCI group name which 
       * gives a pointer to CMachineCtrlClient instance
       *
       * @return         A map of all machines belonging to the fleet
       */ 
      TMachines GetAllMachines();

      /**
       * Changes the timeout time for network service discovery. Default value is 
       * 5000 ms. Change this if you are using slow network, and it seems that not every machine
       * is found by FleetCtrlClient
       *
       * NOTE: Be sure that the network isn't too slow to get replies from all the machines. If 
       *       a machine is not found it is removed from the fleet permanently. If it reappers
       *       a new instance of CMachineCtrlClient is created and the old one is probably not working
       *
       * @param[in] aNewTimeoutTime   Timeout time
       */
      void ChangeServiceDiscoveryTimeoutTime(unsigned int aNewTimeoutTime);      

      /**
       * Changes the frequency of service discovery. Default value is 5000ms, so the service discovery is called
       * every 5 seconds. 
       *
       * NOTE: if servicediscovery timeout time is bigger than this, it can be that the loop is slower than
       * wanted
       *
       * @param[in] aNewTimeoutTime   Timeout time
       */
      void ChangeContinuousServiceDiscoveryLoopTime(unsigned int aNewTimeoutTime);
    private:

      std::string iGIMnetAPAddress;
      unsigned int iGIMnetAPPort;
      std::string iGIMnetName;
      std::string iFleetName;


      std::set<std::string> iMachineNames;
      TMachines iMachines;

      std::map<std::string,gimi::GIMI *> iGIMIInstances; //Every machine has their own gimi instances
      gimi::GIMI *iGIMI;
      MaCI::MaCICtrl::CMaCICtrlClient *iMCC;

      unsigned int iDiscoveryTimeoutTime;
      unsigned int iDiscoveryLoopTime;
      bool iContinuous;
      bool iThreadRunning;
      /// Thread runner function. 
      int ThreadFunction(const int aThreadNumber);
      int ContinuousFleetUpdateThread();
      /**
       * Filters machine
       */
      void FilterMachines( MaCI::MaCICtrl::TServiceEntryArray &aEntries,
                           MaCI::MaCICtrl::TStringArray &aMaCIGroups);


      bool ConstructMachine(std::string aMaCIGroup);
      
      void RemoveUndiscoveredMachines( MaCI::MaCICtrl::TStringArray aMachinesInFleet);
      void DestructFleet();
     //Private copy constructor and assignment operator
      CFleetCtrlClient (const CFleetCtrlClient &):
        iGIMnetAPAddress(""),
        iGIMnetAPPort(0),
        iGIMnetName(""),
        iFleetName(""),
        iMachineNames(),
        iMachines(),
        iGIMIInstances(),
        iGIMI(NULL),
        iMCC(NULL),
        iDiscoveryTimeoutTime(0),
        iDiscoveryLoopTime(0),
        iContinuous(false),
        iThreadRunning(false){}

      CFleetCtrlClient &operator=(const CFleetCtrlClient &) { return *this; }
    };
  }
}
#endif ///< _FLEET_CTRL_CLIENT_HPP
